package com.zbb.online_exam.controller;

import cn.afterturn.easypoi.exception.excel.ExcelImportException;
import com.zbb.online_exam.constant.Method;
import com.zbb.online_exam.dto.JsonResult;
import com.zbb.online_exam.dto.TableDto;
import com.zbb.online_exam.entity.User;
import com.zbb.online_exam.exception.ExamException;
import com.zbb.online_exam.service.UserService;
import com.zbb.online_exam.utils.HttpUtils;
import com.zbb.online_exam.vo.StudentVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.List;

/**
 * @author zbbstart
 * @date 2021/2/9 - 16:55
 */
@RestController
@RequestMapping("teachers")
@Slf4j
@Api(tags = "老师管理功能的相关接口")
public class TeacherManagerController {
    @Autowired
    private HttpUtils httpUtils;
    @Autowired
    private UserService userService;

    /**
     * 获取所有的老师
     */
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @GetMapping
    @ApiOperation(value = "获取所有的老师", notes = "获取角色为老师的所有的用户")
    public JsonResult getAllTeachers(HttpServletRequest req, HttpServletResponse res) {
        JsonResult result = new JsonResult();
        try {
            int pageNo = Integer.parseInt(req.getParameter("page"));
            int pageSize = Integer.parseInt(req.getParameter("limit"));
            log.info("当前老师页码:" + pageNo);
            log.info("页面限制的条数:" + pageSize);
            TableDto tableDto = userService.getAllTeacherUsersByPage(pageNo, pageSize);
            result = httpUtils.buildSuccess(Method.GET, tableDto);
        } catch (ExamException ee) {
            result = httpUtils.buildFailure(ee.getMessage(), Method.GET);
        } catch (Exception e) {
            e.printStackTrace();
            result = httpUtils.build500();
        }
        res.setStatus(result.getCode());
        return result;
    }

    /**
     * 新增老师
     */
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @PostMapping
    @ApiOperation(value = "新增老师", notes = "根据前端传来的用户信息新增到用户表中")
    @ApiImplicitParam(paramType = "header", name = "user", dataType = "User", required = true, value = "前端新增的用户信息")
    public JsonResult addTeacher(@RequestBody User user, HttpServletResponse res) {
        JsonResult result = new JsonResult();
        try {
            userService.insertTeacherUser(user);
            result = httpUtils.buildSuccess(Method.POST, "新增成功!");
        } catch (ExamException ee) {
            result = httpUtils.buildFailure(ee.getMessage(), Method.POST);
        } catch (Exception e) {
            e.printStackTrace();
            result = httpUtils.build500();
        }
        res.setStatus(result.getCode());
        return result;
    }

    /**
     * 修改教师名称
     */
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @PutMapping(value = "{teacherNo}")
    @ApiOperation(value = "修改教师名称", notes = "根据前端传来的用户信息修改教师名称到用户表中")
    public JsonResult updateTeacherName(@ApiParam(name = "teacherNo", value = "老师编号", example = "1") @PathVariable("teacherNo") Integer teacherNo, @RequestBody User user, HttpServletResponse res) {
        JsonResult result = new JsonResult();
        try {
            log.info("要修改的老师编号是:" + teacherNo);
            log.info("修改的老师名称是:" + user.getUsername());
            user.setId(teacherNo);
            userService.updateTeacherName(user);
            result = httpUtils.buildSuccess(Method.PUT, "修改成功!");
        } catch (Exception e) {
            e.printStackTrace();
            result = httpUtils.build500();
        }
        res.setStatus(result.getCode());
        return result;
    }

    /**
     * 删除老师
     * 可以是单个老师的删除，也可以是多个老师的删除
     */
    @PreAuthorize("hasRole('ROLE_ADMIN')")
    @DeleteMapping
    @ApiOperation(value = "删除老师", notes = "根据前端传来的教师编号删除老师")
    public JsonResult deleteUser(@RequestParam("ids") List<Integer> teacherNos, HttpServletResponse res) {
        JsonResult result = new JsonResult();
        log.info("删除老师用户的编号:" + Arrays.toString(teacherNos.toArray()));
        try {
            userService.deleteTeacherUsers(teacherNos);
            result = httpUtils.buildSuccess(Method.DELETE);
        } catch (Exception e) {
            e.printStackTrace();
            result = httpUtils.build500();
        }
        res.setStatus(result.getCode());
        return result;
    }

    /**
     * 当前老师操作的时候新增学生
     */
    @PreAuthorize("hasRole('ROLE_TEACHER')")
    @PostMapping("{teacherNo}")
    @ApiOperation(value = "新增学生", notes = "，登录身份是老师，新增学生所属老师即为当前登录的老师")
    public JsonResult addStudent(@ApiParam(name = "teacherNo", value = "老师编号", example = "5")
                                 @PathVariable("teacherNo") Integer teacherNo,
                                 @RequestBody StudentVo studentVo, HttpServletResponse res) {
        JsonResult result = new JsonResult();
        try {
            studentVo.setTeacherNo(teacherNo);
            userService.insertStudentUser(studentVo);
            result = httpUtils.buildSuccess(Method.POST, "添加成功...");
        } catch (Exception e) {
            e.printStackTrace();
            result = httpUtils.build500();
        }
        res.setStatus(result.getCode());
        return result;
    }

    /**
     * 批量导入学生
     * 可以是单个学生的删除，也可以是多个学生的删除
     */
    @PreAuthorize("hasRole('ROLE_TEACHER')")
    @GetMapping(params = "pathName")
    @ApiOperation(value = "批量导入学生", notes = "根据前端传来的execl模板批量导入学生")
    public JsonResult batchImport(@RequestHeader("auth-token") String token, HttpServletRequest req, HttpServletResponse res) {
        JsonResult result = new JsonResult();
        String pathName = req.getParameter("pathName");
        log.info("文件路径名称:" + pathName);
        try {
            userService.batchImportStudent(token, pathName);
            result = httpUtils.buildSuccess(Method.GET, "批量添加成功..");
        } catch (ExamException e) {
            e.printStackTrace();
            result = httpUtils.build403();
        }catch (ExcelImportException e){
            result = httpUtils.buildFailure(e.getMessage(),Method.GET);
        } catch (Exception e) {
            e.printStackTrace();
            result = httpUtils.build500();
        }
        res.setStatus(result.getCode());
        return result;
    }
}
